<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>角色管理</title>
    <meta name="keywords" content="">
    <meta name="description" content="">

    <link rel="shortcut icon" th:href="@{/favicon.ico}">
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/font-awesome.css}" rel="stylesheet">
    <link th:href="@{/css/animate.css}" rel="stylesheet">
    <link th:href="@{/css/style.css}" rel="stylesheet">
    <link th:href="@{/self/self-common.css}" rel="stylesheet">

    <link th:href="@{/css/plugins/bootstrap-table/bootstrap-table.min.css}" rel="stylesheet">
    <link th:href="@{/css/plugins/bootstrap-select/bootstrap-select.css}" rel="stylesheet">

    <!-- Sweet Alert -->
    <link th:href="@{/css/plugins/sweetalert/sweetalert.css}" rel="stylesheet">

    <!--zTree css引用-->
    <link th:href="@{/self/zTree/metroStyle.css}" rel="stylesheet"/>
    <style type="text/css">
        .tabs-container .panel-body {
            border: none
        }

        .diff-textarea {
            height: auto !important
        }
    </style>
</head>

<body class="gray-bg">

<!--内页左侧布局及树-->
<div class="ui-layout-west ui-layout-west-right">
    <div class="box box-main">
        <div class="box-header">
            <div class="box-title">权限信息</div>
        </div>
        <div class="ui-layout-content">
            <div id="tree" class="ztree"></div>
        </div>
    </div>
</div>
<!--折叠按钮-->
<div class="ui-layout-resizer ui-layout-resizer-open">
    <div class="ui-layout-toggler" title="折叠">
        <span class="ui-content content-open" style="display: block;"><i class="fa fa-caret-left"></i></span>
        <span class="ui-content content-closed" style="display: none;"><i class="fa fa-caret-right"></i></span>
    </div>
</div>
<!--内页左侧布局及树 end-->

<!--内页右侧布局-->
<div class="ui-layout-center">
    <div class="wrapper wrapper-content animated fadeInRight">

        <div class="row">
            <div class="col-sm-12 table-card">
                <div class="ibox ">
                    <div class="ibox-title">
                        <h5>
                            <i class="fa fa-bookmark"></i>
                            角色管理
                        </h5>
                    </div>
                    <div class="ibox-content">
                        <div id="toolbar">
                            <form class="form-inline btnOpacity">

                                <div class="form-group">
                                    <button class="btn btn-purple" type="button" id="roleAddModal">
                                        <i class="fa fa-plus-circle"></i>
                                        新增
                                    </button>
                                </div>
                                <!--                            <div class="btn-group">-->
                                <!--                                <button class="btn btn-orange" type="button" id="btnUpd" onclick="updatePage()">-->
                                <!--                                    <i class="fa fa-pencil-square-o"></i>-->
                                <!--                                    修改-->
                                <!--                                </button>-->
                                <!--                            </div>-->
                                <!--                            <div class="btn-group">-->
                                <!--                                <button class="btn btn-red" type="button" id="btnDelete" onclick="deleteData()">-->
                                <!--                                    <i class="fa fa-times"></i>-->
                                <!--                                    删除-->
                                <!--                                </button>-->
                                <!--                            </div>-->
                            </form>

                        </div>

                        <table id="dataTable" data-mobile-responsive="true"></table>
                    </div>
                </div>
            </div>
        </div>


        <!--    新增-->
        <div class="modal inmodal fade" id="myModalAdd">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">新增角色</h4>
                        <button type="button" class="close" data-dismiss="modal">×</button>
                    </div>
                    <div class="modal-body">

                        <div class="col-md-12 jsmc">
                            <div class="tabs-container">

                                <ul class="nav nav-tabs">
                                    <li class="active"><a data-toggle="tab" href="#tab-1-Add"
                                                          aria-expanded="true">角色名称</a>
                                    </li>
                                    <li class=""><a data-toggle="tab" href="#tab-2-Add" aria-expanded="false">权限</a>
                                    </li>
                                </ul>

                                <div class="tab-content">
                                    <div id="tab-1-Add" class="tab-pane active">
                                        <div class="panel-body">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <strong class="col-sm-2">角色名称：</strong>
                                                    <div class="col-sm-9">
                                                        <input id="roleNameAdd" type="text" name="" class="form-control"
                                                               placeholder="请输入角色名称">
                                                    </div>
                                                </div>
                                                <div class="form-group">
                                                    <strong class="col-sm-2">备注：</strong>
                                                    <div class="col-sm-9">
                                                        <textarea class="form-control diff-textarea" id="commentAdd"
                                                                  rows="6" autocomplete="off"
                                                                  placeholder="请输入备注..."></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="tab-2-Add" class="tab-pane">
                                        <div class="panel-body">
                                            <div>
                                                <div id="searchTreeAddTest" class="ztree"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-close" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-purple btn-save" id="btnAddSave">保存</button>
                    </div>
                </div>
            </div>
        </div>

    </div>

</div>

<!-- 全局js -->
<script th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/content.js}"></script>
<script th:src="@{/js/app.js}" type="text/javascript"></script>

<!-- Bootstrap table -->
<script th:src="@{/js/plugins/bootstrap-table/bootstrap-table.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js}"></script>
<!--提示框-->
<script th:src="@{/js/plugins/layer/layer.min.js}"></script>
<!--下拉选择框-->
<script th:src="@{/js/plugins/bootstrap-select/bootstrap-select.js}"></script>
<!--日期-->
<script th:src="@{/js/plugins/layer/laydate/laydate.js}"></script>

<!--bootstrap导出-->
<script th:src="@{/js/plugins/bootstrap-table-export/bootstrap-table-export.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table-export/tableExport.js}"></script>
<!--pdf导出 文本乱码问题-->
<script th:src="@{/js/plugins/bootstrap-table-export/pdfmake/pdfmake.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table-export/pdfmake/gbsn00lp_fonts.js}"></script>
<!--将表导出为PDF文件-->
<script th:src="@{/js/plugins/bootstrap-table-export/pdfmake/jspdf.min.js}"></script>
<script th:src="@{/js/plugins/bootstrap-table-export/pdfmake/jspdf.plugin.autotable.js}"></script>

<!-- Bootstrap table X-editable-->
<!--<script th:src="@{/js/plugins/bootstrap3-editable/js/bootstrap-editable.js}" type="text/javascript"></script>-->
<!--<script th:src="@{/js/plugins/bootstrap-table/extensions/editable/bootstrap-table-editable.js}" type="text/javascript"></script>-->
<!--<script th:src="@{/js/plugins/suggest/bootstrap-suggest.min.js}" type="text/javascript"></script>-->


<script th:src="@{/js/plugins/treeview/bootstrap-treeview.js}"></script>
<script th:src="@{/js/plugins/sweetalert/sweetalert.min.js}"></script>

<!--zTree js引用-->
<script th:src="@{/self/zTree/jquery.ztree.all.min.js}"></script>
<script th:src="@{/self/zTree/self-zTree.js}"></script>

<script>
    var treeData = "";
    var myMap = {};//创建map集合
    var roleId = -1, roleName = '', roleComment = '';
    $(document).ready(function () {

        function queryParams(params) {
            return {
                pageSize: params.pageSize,
                pageNumber: params.pageNumber,
                searchText: params.searchText === undefined ? "" : params.searchText
            }
        }

        $('#dataTable')
            .bootstrapTable({
                url: baseUrl + "getRoleListPage",
                method: "post",
                queryParamsType: "",
                queryParams: queryParams,
                pageNumber: 1, //初始化加载第一页，默认第一页
                pageSize: 10, //每页的记录行数（*）
                striped: false, //是否显示行间隔色
                cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                search: false, //是否显示搜索框功能
                pagination: true, //是否分页
                showRefresh: false, //是否显示刷新功能
                showToggle: false,
                showColumns: false,
                clickToSelect: true, //是否启用点击选中行
                // uniqueId: "indentId", //每一行的唯一标识，一般为主键列
                // idField: "indentId",
                formatSearch: function () {
                    return "角色名称";
                },
                iconSize: 'outline',
                sidePagination: "server", //服务端请求
                showExport: false,//显示导出按钮
                buttonsAlign: "right",  //按钮位置
                exportTypes: ['excel'],  //导出文件类型
                pageList: [10, 20, 30, 'all'],
                exportDataType: "basic",//导出类型 'basic':当前页, 'all', 'selected'.
                exportOptions: {
                    ignoreColumn: [3],  //忽略某一列的索引
                    // fileName: '总台帐报表',  //文件名称设置
                    // worksheetName: 'sheet1',  //表格工作区名称
                    // tableName: '总台帐报表',
                },
                toolbar: '#toolbar', //工具按钮用哪个容器
                icons: {
                    refresh: 'glyphicon-repeat',
                    toggle: 'glyphicon-list-alt',
                    columns: 'glyphicon-list',
                    export: 'glyphicon-export'
                }
                , responseHandler: function (res) {
                    var rows = [];
                    if (res.total !== 0) {
                        rows = res.list;
                    }
                    var result = {
                        rows: rows,
                        total: res.total
                    };

                    return result;
                },
                // onEditableSave: function (field, row, oldValue, $ele) {
                //     //更新数据到数据库
                // },
                columns: [
                    /* {
                     width: 30,
                     title: '序号',
                     formatter: function (value, row, index) {
                         return index + 1;
                     }
                 }, */
                    {
                        field: 'roleName',
                        title: '角色名称'
                    }, {
                        field: 'createTime',
                        title: '创建时间'
                    }, {
                        field: 'comment',
                        title: '备注',
                        formatter: function (value, row, index) {
                            if (row.comment) {
                                return row.comment;
                            } else {
                                return "";
                            }
                        }
                    }, {
                        field: 'operation',
                        title: '操作',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var resUpdate = "<button type='button' class = 'btn btngroup btn-xs czIcon icon_edit'  onclick='updatePage(\"" + row.roleName + "\",\"" + row.comment + "\",\"" + row.roleId + "\")'title='编辑'></button>";
                            var resDel = "<button type='button' class = 'btn btngroup btn-xs czIcon icon_close'  onclick='deleteData(\"" + row.roleId + "\")'title='删除'></button>";
                            return resUpdate + resDel;
                        }
                    }
                ],
                //获取table点击行id
                onClickRow: function (row, $element) {
                    $('.info').removeClass('info');
                    $($element).addClass('info');
                    roleId = row.roleId;
                    roleComment = row.comment;
                    roleName = row.roleName;
                    showRightTree(row.roleId);
                },
            });

        $("#myModalAdd").on("hidden.bs.modal", function () {
            $("#roleNameAdd").val('');
            $("#commentAdd").val('');
        })
    });

    //删除
    function deleteData() {
        // if (!roleId || roleId == -1) {
        //     layer.msg("请选择角色");
        //     return
        // }
        swal({
            title: "确定删除该角色吗？",
            //text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "取消",
            confirmButtonColor: "rgb(85 221 218)",
            confirmButtonText: "确定",
            closeOnConfirm: false
        }, function () {
            PostWebApi("deleteRole", {
                roleId: roleId
            }).done(function (data) {
                console.log(data);
                if (data.code === 0) {
                    swal.close()
                    layer.msg('删除成功');
                    $('#dataTable').bootstrapTable('refresh');
                    roleId = -1;
                    showRightTree(roleId);
                } else {
                    layer.msg('删除失败');
                }
            });
        })
    }

    var zTreeObjRight; //定义ztree对象
    var settingsRight = {
        view: {
            showIcon: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true, //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "id", //节点数据中保存唯一标识的属性名称
                pIdKey: "pId", //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "name" //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false, //true 、 false 分别表示 显示 、不显示 复选框或单选框
            nocheckInherit: true //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onClick: chooseNode
        }
    };

    function chooseNode(event, treeId, treeNode) {
        ztreeStyle(event, treeId, treeNode)//改变ztree样式
    }

    function showRightTree(roleId) {
        PostWebApi("getPerByRoleId", {
            roleId: roleId
        }).done(function (data) {
            if (data.code == 0) {
                var info = data.data;
                if (info) {
                    zTreeObjRight = $.fn.zTree.init($("#tree"), settingsRight, info); //初始化树
                    zTreeObjRight.expandAll(true); //true 节点全部展开、false节点收缩
                }
            }
        })
    }

    var zTreeObj; //定义ztree对象
    // var selectarry=[]; //要勾选的id
    var settingss = {
        view: {
            showIcon: false,
            showLine: false
        },
        data: {
            simpleData: {
                enable: true, //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "id", //节点数据中保存唯一标识的属性名称
                pIdKey: "pId", //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "name" //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: true, //true 、 false 分别表示 显示 、不显示 复选框或单选框
            nocheckInherit: true //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        }
    };
    var modalType = "";
    // 展示信息
    $("#roleAddModal").click(function () {
        var roleIds = -1;
        initZtree(roleIds);
        modalType = "ADD";
        $("#myModalAdd").find("h4").text("新增角色");
        $("#myModalAdd").modal('show');
    })

    function updatePage(name,comment,id) {
        // if (!roleId || roleId == -1) {
        //     layer.msg("请选择角色");
        //     return
        // }
        initZtree(id)
        roleId=id
        roleComment=comment,
            roleName=name
        modalType = "UPDATE";
        $("#myModalAdd").find("h4").text("编辑角色");
        $("#roleNameAdd").val(roleName!=null ? roleName : '');
        $("#commentAdd").val(roleComment != 'null' ? roleComment : '');
        $("#myModalAdd").modal('show');
    }

    //编辑计划
    $("#btnAddSave").click(function () {
        if (modalType) {
            if (modalType == 'ADD') {
                addRole();
            } else {
                updateRole();
            }
        }
    });

    // 新增
    function addRole() {
        var roleName = $("#roleNameAdd").val();
        if (roleName === "") {
            layer.msg('角色名称不可为空');
            return false;
        }
        var comment = $.trim($("#commentAdd").val());
        myMap = {};
        var chkNodeArr = zTreeObj.getCheckedNodes(true); //true获取选中节点,false未选中节点,默认为true
        for (var i = 0; i < chkNodeArr.length; i++) {
            myMap[chkNodeArr[i].id] = chkNodeArr[i].name;
        }
        //console.log(myMap)
        if (myMap.length < 1) {
            layer.msg('请选择角色权限');
            return false;
        }
        PostWebApi("addRole", {
            roleName: roleName,
            comment: comment,
            maps: myMap
        }).done(function (data) {
            if (data.code === 0) {
                layer.msg('新增成功');
                $("#myModalAdd").modal('hide');
                $('#dataTable').bootstrapTable('refresh');
                roleId = -1;
                showRightTree(roleId);
            } else {
                layer.msg(data.msg);
            }
        });
    }

    //保存变更
    function updateRole() {
        var roleName = $("#roleNameAdd").val();
        if (roleName === "") {
            layer.msg('角色名称不可为空');
            return false;
        }
        var comment = $.trim($("#commentAdd").val());
        myMap = {};
        var chkNodeArr = zTreeObj.getCheckedNodes(true); //true获取选中节点,false未选中节点,默认为true
        for (var i = 0; i < chkNodeArr.length; i++) {
            myMap[chkNodeArr[i].id] = chkNodeArr[i].name;
        }
        if (myMap.length < 1) {
            layer.msg('请选择角色权限');
            return false;
        }
        PostWebApi("updateRole", {
            roleId: roleId,
            roleName: roleName,
            comment: comment,
            maps: myMap
        }).done(function (data) {
            if (data.code === 0) {
                layer.msg('编辑成功');
                $("#myModalAdd").modal('hide');
                $('#dataTable').bootstrapTable('refresh');
                roleId = -1;
                showRightTree(roleId);
            } else {
                layer.msg(data.msg);
            }
        });
    }

    function initZtree(roleId) {
        PostWebApi("showModalTree", {
            roleId: roleId
        }).done(function (data) {
            if (data.code == 0) {
                var info = data.data;
                if (info) {
                    zTreeObj = $.fn.zTree.init($("#searchTreeAddTest"), settingss, info); //初始化树
                    zTreeObj.expandAll(false); //true 节点全部展开、false节点收缩
                }
            }
        })
    }

</script>


</body>

</html>
